package com.ikun.kunpicturebackend.manager.websocket.disruptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ikun.kunpicturebackend.domain.User;
import com.ikun.kunpicturebackend.manager.websocket.PictureEditHandler;
import com.ikun.kunpicturebackend.manager.websocket.model.PictureEditMessageTypeEnum;
import com.ikun.kunpicturebackend.manager.websocket.model.PictureEditRequestMessage;
import com.ikun.kunpicturebackend.manager.websocket.model.PictureEditResponseMessage;
import com.ikun.kunpicturebackend.model.vo.UserVO;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * 事件处理器-消费者
 */
@Component
@Slf4j
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {

    @Resource
    @Lazy
    private PictureEditHandler pictureEditHandler;

    @Override
    public void onEvent(PictureEditEvent event) throws Exception {
        // 获取图片编辑请求消息
        PictureEditRequestMessage pictureEditRequestMessage = event.getPictureEditRequestMessage();
        // 当前用户session
        WebSocketSession session = event.getSession();
        User user = event.getUser();
        Long pictureId = event.getPictureId();
        // 消息类别
        String type = pictureEditRequestMessage.getType();
        PictureEditMessageTypeEnum messageTypeEnum = PictureEditMessageTypeEnum.valueOf(type);

        // 根据消息的类型进行不同的处理
        switch (messageTypeEnum) {
            // 进入编辑
            case ENTER_EDIT:
                pictureEditHandler.handleEnterEditMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            // 编辑动作
            case EDIT_ACTION:
                pictureEditHandler.handleEditActionMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            // 退出编辑
            case EXIT_EDIT:
                pictureEditHandler.handleExitEditMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            default:
                // 构造响应消息
                PictureEditResponseMessage pictureEditResponseMessage = new PictureEditResponseMessage();
                pictureEditResponseMessage.setType(PictureEditMessageTypeEnum.ERROR.getValue());
                pictureEditResponseMessage.setMessage("消息类型错误");
                pictureEditResponseMessage.setUserVO(BeanUtil.copyProperties(user, UserVO.class));
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditResponseMessage)));
        }
    }
}
